import { ref, computed } from 'vue'
import { getUserDetail } from '@/api/user.js'

// 用户状态
const user = ref(null)
const isAuthenticated = ref(false)

// 获取当前用户信息
export function useAuth() {
  // 从 localStorage 获取用户信息
  const getCurrentUser = () => {
    const token = localStorage.getItem('token')
    if (token) {
      try {
        // 解析 JWT token 获取用户ID
        const tokenParts = token.split('.')
        if (tokenParts.length >= 2) {
          const payload = JSON.parse(atob(tokenParts[1]))
          return {
            id: payload.UserId,
            username: payload['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name'] || 'admin'
          }
        }
      } catch (error) {
        console.error('解析token失败:', error)
        return null
      }
    }
    return null
  }

  // 初始化用户信息
  const initUser = () => {
    const currentUser = getCurrentUser()
    if (currentUser) {
      user.value = currentUser
      isAuthenticated.value = true
    }
  }

  // 获取用户详细信息
  const loadUserDetail = async () => {
    if (user.value?.id) {
      try {
        const response = await getUserDetail(user.value.id)
        if (response.code === 200 && response.data) {
          user.value = {
            ...user.value,
            ...response.data
          }
        }
      } catch (error) {
        console.error('获取用户详情失败:', error)
      }
    }
  }

  // 登出
  const logout = () => {
    localStorage.removeItem('token')
    user.value = null
    isAuthenticated.value = false
  }

  // 初始化
  if (!user.value) {
    initUser()
  }

  return {
    user: computed(() => user.value),
    isAuthenticated: computed(() => isAuthenticated.value),
    loadUserDetail,
    logout
  }
}
